/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package encaps.utils;

import encaps.entities.Genre;
import javax.sql.DataSource;
import encaps.utils.DatabaseUtil;
import javax.naming.NamingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
 *  
 * @author fon_Valter\\remake Artem
 */
public class GenreManager {
    private Connection conn = null;
    private DataSource dataSource;
    private PreparedStatement ps;
    private HashSet availableGenres;
    public GenreManager() throws NamingException {
        dataSource = DatabaseUtil.getDataSource();
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("SELECT * FROM genre");
            ResultSet rs = ps.executeQuery();
            availableGenres = new HashSet();
            while(rs.next()) {
                availableGenres.add(rs.getString(1));
            }
        } catch(SQLException ex) {
          //
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }

    public Set getAvailableGenres() {
        return (Set)availableGenres; 
    }
// TODO static:
    public void createGenre(String name) throws SQLException {
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("INSERT INTO genre(name) VALUES(?)");
            ps.setString(1, name);
            if (ps.executeUpdate() != 1) {
                throw new SQLException("Insertion error");
            }
            availableGenres.add(name);
//        } catch(SQLException ex) {
            
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }
// TODO static:    
    public void deleteGenre(String name) throws SQLException {
        try {
            conn = dataSource.getConnection();
            ps = conn.prepareStatement("DELETE FROM genre WHERE name=?");
            ps.setString(1, name);
            if (ps.executeUpdate() != 1) {
                throw new SQLException("Delete error");
            }
       // } catch(SQLException ex) {
            availableGenres.remove(name);
        } finally {
            DatabaseUtil.closeConnection(conn, ps);
        }
    }
}
            
